package sicau.carManager.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import sicau.carManager.Util.ExcelUtil.ExcelDataListener;
import sicau.carManager.Util.ExcelUtil.ExcelUtil;
import sicau.carManager.entity.Admin;
import sicau.carManager.entity.FixedCarInformation;
import sicau.carManager.result.R;
import sicau.carManager.service.FixedCarInformationService;
import sicau.carManager.service.ViolationInformationService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ITcz
 * @since 2021-02-05
 */
@Slf4j
@RestController
@RequestMapping("/fixed-car-information")
@CrossOrigin
public class FixedCarInformationController {

    @Autowired
    ViolationInformationService vioService;

    @Autowired
    FixedCarInformationService fixService;

    @ApiOperation("输入车牌或车主姓名查询车辆信息,车主姓名查询方式只限于固定车（预约车待加入该功能）！" +
            "车牌查询返回结果为单个车辆信息即：map（车辆信息），而车主姓名查询可能重名，所以返回为：List(map（车辆信息）)")
    @GetMapping("select/car/information")
    public R selectCarInformation(Admin admin,
                                  @ApiParam("查询方式0代表车牌查，1代表车主姓名查") @RequestParam("method") Integer method,
                                  @ApiParam("车牌") @RequestParam(value = "licensePlate", required = false) String licensePlate,
                                  @ApiParam("车主姓名") @RequestParam(value = "name", required = false) String name){
        String campus = admin.getCampus();
        //判断车牌和车主姓名是否同时为空
        boolean isNull = (licensePlate == null && name == null);
        if (method == null || isNull) {
            return R.error(500200, "查询方式不确定或车牌与车主姓名同时为空");
        }
        HashMap resMap = new HashMap();

        //车牌查询方式
        if (licensePlate != null) {
            //查询车辆违章次数
            Integer vioNumber = vioService.selectViolationNumByPlateNum(licensePlate, campus);
            //查询车辆信息，如果是固定车有相关信息，如果是预约车可能有电话，如果是临时车则无信息
            FixedCarInformation carInformation = fixService.selectCarByPlateNum(licensePlate, campus);
            resMap.put("违规停车次数", vioNumber);
            resMap.put("车辆信息", carInformation);
            return R.ok(resMap);
        }

        //车主姓名查询方式
        //查询车辆信息,有可能重名，所以返回List集合
        List<FixedCarInformation> carInformations = fixService.selectCarByName(name);
        if (carInformations.size() == 0) {
            return R.ok("无此车主违规停车信息");
        }
        //依次从List中取出重名车主的车牌号，并获取车辆违停次数，封装于resMap内
        List<HashMap> resCarInformationList = new ArrayList<>();
        for(FixedCarInformation carInformation : carInformations) {
            //通过车牌查询车辆违章次数
            Integer vioNumber = vioService.selectViolationNumByPlateNum(carInformation.getLicensePlateNumber(), campus);
            HashMap map = new HashMap();
            map.put("违规停车次数", vioNumber);
            map.put("车辆信息", carInformation);
            map.put("车牌", carInformation.getLicensePlateNumber());
            resCarInformationList.add(map);
        }
        resMap.put("违章信息：", resCarInformationList);
        return R.ok(resMap);
    }

    @PostMapping("/upload/information/excel")
    @ApiOperation("通过Excel表格导入固定车辆信息")
    public R uploadExcel(Admin admin, @ApiParam("Excel文件") @RequestParam("filename") MultipartFile file) throws IOException {
        //TeacherExcel.class是实体类，
        //fixService是持久层的接口
        String campus = admin.getCampus();
        ExcelReader excelReader = null;
        try {
            //文件输入流
            InputStream inputStream = file.getInputStream();
            //调用方法进行读取
            //这里必须用new ExcelDataListener，不能被spring管理
            EasyExcel.read(inputStream, FixedCarInformation.class,new ExcelDataListener(fixService, campus)).sheet().doRead();
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            if (excelReader != null) {
                // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
                excelReader.finish();
            }
        }
        return R.ok();
    }


    /*下载模板*/
    @GetMapping("/download/information/Excel")
    @ApiOperation("将固定车辆信息以Excel表格方式导出")
    public void downloadExcel(Admin admin, HttpServletResponse response) throws UnsupportedEncodingException {
        String fileName = "固定车辆信息";
        String sheetName = "固定车辆信息";
        String campus = admin.getCampus();
        //查询校区所有的固定车信息
        List<FixedCarInformation> fixedCarInformationList = fixService.selectAllFixedCarInformation(campus);
        System.out.println(fixedCarInformationList);
        try {
            //FixedCarInformation.class是实体类
            //fixedCarInformationList是需要导出的List实体类信息
            //导出车辆信息的excel文件
            ExcelUtil.writeExcel(response,fixedCarInformationList,fileName,sheetName,FixedCarInformation.class);
        } catch (Exception e) {
            log.error("导出文档出错：", e.getCause());
        }
    }
}

